package com.yand.data.link;


/**
 * 单链表
 */
public class LinkedList {

     //链表头
     private Link first;



     //链表的添加（头部添加）
     public void addToHead(long data){
         Link link = new Link(data);
         if(first == null){
             first = link;
         }else{
             //这么做的话，再次添加的时候，咋办？？？
             //first.setNext(link);
             //这么做 nice
             link.setNext(first);
             first = link;
         }
     }


     //链表的添加 从尾部添加
     void addToEnd(long data){
         Link targetLink = new Link(data);
         //遍历链表，找到getNext == null 的链表对象， 添加进原链表中
         if(first == null){
             first = targetLink;
         }else {
             Link oldLink = first;
             Link up = null;
             while (oldLink.getNext() != null) {
                 oldLink = oldLink.getNext();
             }
             oldLink.setNext(targetLink);
         }
     }



     //根据位置添加链表
     void addByIndex(long data, int index){
         Link up = first;

         Link next = first;

         if(index == 0){
             addToHead(data);
         }else{
             Link targetLink = new Link(data);

             for(int i = 0 ; i < index; i ++){
                 up = next;
                 next = next.getNext();
             }
             targetLink.setNext(next);
             up.setNext(targetLink);

         }





     }



     //遍历链表
     void disPlay(){
         Link list =  first;

         while (list != null){
             System.out.print(list.getData()+" ");
             list = list.getNext();
         }
     }


     //根据值删除 单链表结构
     void del(long data){
         // 遍历这个链表
         Link next = first;
         Link up = first;
         //这边 循环的条件为 ！= data
         while(next.getData() != data ){
             if(next.getNext() == null){
                 throw new RuntimeException("该链表中没有该元素");
             }
             up = next;
             next =next.getNext();
         }

        //说明删除的是第一个对象
         if(next == first){
             first = first.getNext();
         }else{
             //获取下一个链表值
             Link endLink = next.getNext();

             up.setNext(endLink);
         }
     }




    class Link{

        private long data;

        private Link next;


        public Link(long data){
            this.data = data;
        }

        public void setData(long data) {
            this.data = data;
        }

        public void setNext(Link next) {
            this.next = next;
        }


        public Link getNext() {
            return next;
        }


        public long getData() {
            return data;
        }
    }







}


